<template>
  <div>
    <h3>商品管理 - 添加商品</h3>
    <el-form :model="productDto" ref="productForm" label-width="120px" :rules="rules">
      <el-form-item label="选择店铺" prop="merchantId">
        <el-select v-model="productDto.merchantId" placeholder="请选择店铺">
          <el-option
              v-for="merchant in merchantList"
              :key="merchant.id"
              :label="merchant.shopName"
              :value="merchant.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="productDto.name" placeholder="请输入商品名称"></el-input>
      </el-form-item>
      <el-form-item label="商品描述" prop="description">
        <el-input v-model="productDto.description" placeholder="请输入商品描述"></el-input>
      </el-form-item>
      <el-form-item label="商品价格" prop="price">
        <el-input v-model="productDto.price" placeholder="请输入商品价格"></el-input>
      </el-form-item>
      <el-form-item label="商品库存" prop="stock">
        <el-input v-model="productDto.stock" placeholder="请输入商品库存"></el-input>
      </el-form-item>
      <el-form-item label="商品单位" prop="unit">
        <el-input v-model="productDto.unit" placeholder="请输入商品单位"></el-input>
      </el-form-item>
      <el-form-item label="商品产地" prop="origin">
        <el-input v-model="productDto.origin" placeholder="请输入商品产地"></el-input>
      </el-form-item>
      <el-form-item label="商品图片" prop="imageUrls">
        <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :before-upload="beforeImageUpload"
            :http-request="customImageUpload"
            :on-change="handleImageChange"
        >
          <div class="avatar-wrapper">
            <img
                v-if="productDto.imageUrls"
                :src="productDto.imageUrls"
                class="avatar-image"
            />
            <div v-else class="avatar-placeholder">
              <el-icon class="upload-icon"><Plus /></el-icon>
              <span class="upload-text">上传商品图片</span>
            </div>
            <div class="upload-mask">
              <el-icon class="upload-icon"><Edit /></el-icon>
              <span class="upload-text">更换图片</span>
            </div>
          </div>
          <div class="mt-2 text-sm text-gray-500">商品图片为必填项，图片大小不能超过5MB</div>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addProduct">添加商品</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import { Plus, Edit } from '@element-plus/icons-vue'

// 从 localStorage 获取用户信息
const userStr = localStorage.getItem('merchant');
const user = userStr ? JSON.parse(userStr) : null;

// 默认图片
const defaultImage = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';

// 定义表单数据
const productDto = ref({
  merchantId: null,
  name: '',
  description: '',
  price: '',
  stock: '',
  unit: '',
  origin: '',
  imageUrls: '',
  sales: 0,
  status: 1, // 默认为待审核状态
});

// 表单验证规则
const rules = reactive({
  merchantId: [
    { required: true, message: '请选择店铺', trigger: 'change' }
  ],
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 100, message: '商品名称长度在2-100个字符之间', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入商品描述', trigger: 'blur' },
    { max: 255, message: '商品描述不能超过255个字符', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的价格格式', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入商品库存', trigger: 'blur' },
    { pattern: /^\d+$/, message: '请输入正确的库存数量', trigger: 'blur' }
  ],
  unit: [
    { required: true, message: '请输入商品单位', trigger: 'blur' },
    { max: 20, message: '商品单位不能超过20个字符', trigger: 'blur' }
  ],
  origin: [
    { required: true, message: '请输入商品产地', trigger: 'blur' },
    { max: 50, message: '商品产地不能超过50个字符', trigger: 'blur' }
  ],
  imageUrls: [
    { required: true, message: '请上传商品图片', trigger: 'change' }
  ]
});

// 表单引用
const productForm = ref(null);

// 定义店铺列表
const merchantList = ref([]);

// 获取店铺列表
const getMerchantList = async () => {
  try {
    // 发送查看店铺请求
    const response = await axios.get(`${BASE_URL}/api/v1/merchant/selStore`, {
      withCredentials: true
    });
    if (response.data.code === 2000) {
      merchantList.value = response.data.data;
    } else {
      ElMessage.error(response.data.msg || '获取店铺列表失败');
    }
  } catch (error) {
    console.error('获取店铺列表失败:', error);
    ElMessage.error('获取店铺列表失败，请稍后重试');
  }
};

// 自定义图片上传
const customImageUpload = async (options) => {
  const {file} = options;
  try {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('userId', user?.id || '123');

    const response = await axios.post(`${BASE_URL}/v1/file/upload`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': `Bearer ${user?.token || ''}`
      }
    });

    if (response.data.code === 2000) {
      ElMessage.success('图片上传成功');
      productDto.value.imageUrls = response.data.data; // 直接存储图片URL字符串
    } else {
      throw new Error(response.data.message || '上传失败');
    }
  } catch (error) {
    ElMessage.error('上传出错：' + error.message);
    throw error;
  }
};

// 图片变化处理
const handleImageChange = (file) => {
  // 这里可以添加额外的处理逻辑
};

// 上传前校验
const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return false;
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!');
    return false;
  }

  return isImage && isLt5M;
};

// 定义添加商品方法
const addProduct = async () => {
  // 表单验证
  productForm.value.validate(valid => {
    if (!valid) {
      ElMessage.error('请完善商品信息');
      return;
    }

    // 发送添加商品请求
    axios.post(`${BASE_URL}/api/v1/merchant/addProduct`, productDto.value)
        .then(response => {
          if (response.data.code === 2000) {
            ElMessage.success('商品添加成功');
            // 清空表单
            productDto.value = {
              merchantId: null,
              name: '',
              description: '',
              price: '',
              stock: '',
              unit: '',
              origin: '',
              imageUrls: '',
              status: 0
            };
          } else {
            ElMessage.error(response.data.msg || '添加商品失败');
          }
        })
        .catch(error => {
          console.error('添加商品失败:', error);
          ElMessage.error('添加商品失败，请稍后重试');
        });
  });
};

// 页面挂载时获取店铺列表
onMounted(() => {
  getMerchantList();
});
</script>

<style scoped>
.avatar-uploader {
  --el-avatar-size: 178px;
}

.avatar-wrapper {
  position: relative;
  width: var(--el-avatar-size);
  height: var(--el-avatar-size);
  border-radius: 6px;
  overflow: hidden;
  border: 1px dashed var(--el-border-color);
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  color: #8c939d;
  background-color: #f5f7fa;
}

.upload-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  opacity: 0;
  transition: opacity 0.3s;
}

.avatar-wrapper:hover .upload-mask {
  opacity: 1;
}

.upload-icon {
  font-size: 28px;
  margin-bottom: 8px;
}

.upload-text {
  font-size: 14px;
}

.mt-2 {
  margin-top: 0.5rem;
}

.text-sm {
  font-size: 0.875rem;
  line-height: 1.25rem;
}

.text-gray-500 {
  color: #6b7280;
}
</style>